import React, { useState, useEffect, useRef } from 'react';
import { connect } from 'react-redux';
import { View, Text, Image, ScrollView } from '@tarojs/components';
import Taro, { getCurrentInstance, useDidShow } from '@tarojs/taro';
import utils from '@/utils/index';
import { debounce } from '@/utils/helper';
import { sourceUrl } from '@/config';
import Imagelocation from '@/components/Imagelocation';
import Icon from '@/components/Icon';
import { customeColor } from '@/src/config';
import pBack from '@/images/common/back.svg';
import pZhekou from '@/images/common/zhekou.png';
import pUpWhite from '@/images/common/upWhite.png';
import cartImg from '@/images/standBar/cart.png';
import CommentList from '@/components/Comment/List';
import { getCommentCountServer, getCommentScoreServer } from '@/services/comment';
import CommentFilter from '@/components/Comment/Filter';
import CommentScoreInfo from '@/components/Comment/ScoreInfo';
import CommentImagePreview from '@/components/Comment/ImagePreview/index';
import { checkProductIsSoldOut } from '@/dataTransfer/product';

import { checkDistributionWay } from '@/pages/mainPages/standardCartPage/orgView/helper';
import DistributionWayLayout from '@/pages/mainPages/standardCartPage/orgView/DistributionWayLayout';

import Tabs from './tabs';
import ShoppingCarList from './shoppingCar/index';
import SkuSelect from './skuSelect/index';
import './index.scss';
import Sold from './sold';
import EmptyProduct from '../../components/EmptyProduct';
import Delivery from './delivery/index';
import AddressSelect from '../goodsDetail/addressSelect';

const bar = {
  back: true,
};
const background = {
  backgroundColor: '#ffffff',
};

let timer = null;

// 右侧每一类的 bar 的高度（固定）
const RIGHT_BAR_HEIGHT = utils.getSizeByScale(58 + 16);
// 右侧每个子类的高度（固定）
const RIGHT_ITEM_HEIGHT_NORMAL = utils.getSizeByScale(160);
const RIGHT_ITEM_HEIGHT_ZHEKOU = utils.getSizeByScale(194);
const RIGHT_ITEM_HEIGHT_DISTANCE = utils.getSizeByScale(24);
const RIGHT_ITEM_HEIGHT_DISTANCE_LAST = utils.getSizeByScale(8);
// 左侧每个类的高度（固定）
const LEFT_ITEM_HEIGHT = utils.getSizeByScale(82);

const goBackPage = () => {
  Taro.navigateBack();
};

const TakeOutShopPage = ({
  takeOutProductsList,
  allAddresses = [],
  selectedAddress = {},
  dispatch,
}) => {
  const refCommentList = useRef(null);

  const [currentTab, setCurrentTab] = useState(0);
  const [shop, setShop] = useState({});
  const [productList, setProductList] = useState({});
  const [categoryList, setCategoryList] = useState([]);
  const [hasGot, setHasGot] = useState(false);
  const [curLeftSelect, setCurLeftSelect] = useState(null);
  const [curLeftToTop, setCurLeftToTop] = useState(0);
  const [curRightToTop, setCurRightToTop] = useState(0);
  const [carProList, setCarProList] = useState([]);
  const [isOpenedCar, setIsOpenedCar] = useState(false);
  const [isOpenedSku, setIsOpenedSku] = useState(false);
  const [isOpenedDelivery, setIsOpenedDelivery] = useState(false);
  const [isOpenedAddrList, setIsOpenedAddrList] = useState(false);
  const [productCur, setProductCur] = useState({});
  const [curLocation, setCurLocation] = useState(null);
  const urlParms = useRef({});
  const eachRightItemToTop = useRef(null);
  const lastgroupProExtendDom = useRef([]);
  const preventScrollHandle = useRef(false);
  const hasGetCar = useRef(false);
  const [soldGoods, setSoldGoods] = useState(undefined);
  const [isEmptyProduct, setIsEmptyProduct] = useState(false);
  const [commentFilter, setCommentFilter] = useState(0);
  const [commentHasPicCount, setCommentHasPicCount] = useState(0);
  const [commentGoodCount, setCommentGoodCount] = useState(0);
  const [commentScore, setCommentScore] = useState([]);
  const [delivery, setDelivery] = useState(null);
  const [totalMoney, setTotalMoney] = useState({ totalPayment: 0, totalPrice: 0 });
  const [distributionWayGroup, setDistributionWayGroup] = useState();

  const [tabsList, setTabsList] = useState([
    {
      label: '点菜',
      value: 0,
    },
    {
      label: '评价',
      value: 1,
      ext: '(0)',
    },
  ]);

  const handleTabChanged = (index) => {
    setCurrentTab(index);
  };

  const handleCommentFilter = (index) => {
    setCommentFilter(index);
  };

  const handleSoldClose = () => {
    setSoldGoods(undefined);
  };

  useEffect(() => {
    urlParms.current = getCurrentInstance().router.params;
    getCategoryProducts();
  }, []);

  useEffect(() => {
    if (Object.keys(selectedAddress).length == 0) {
      getLocation();
    }
  }, []);

  useEffect(() => {
    if (curLocation !== null || Object.keys(selectedAddress).length > 0) {
      getShopInfo();
    }
  }, [curLocation, selectedAddress]);

  useEffect(() => {
    if (Object.keys(selectedAddress).length > 0) {
      getCarProList();
    }
  }, [selectedAddress]);

  useEffect(() => {
    takeOutProductsList && dealCategoryProduct();
  }, [takeOutProductsList]);

  useEffect(() => {
    let cgLen = Object.keys(productList).length;
    if (cgLen > 0 && eachRightItemToTop.current == null) {
      eachRightItemToTop.current = getEachRightItemToTop();
      getLastgroupProExtendDom();
      setCurLeftSelect(categoryList[0].id);
    }
  }, [productList]);

  useEffect(() => {
    let tmpProductList = { ...productList };
    let cgLen = Object.keys(productList).length;
    if (cgLen > 0) {
      if (carProList.length > 0) {
        for (let cg = 0; cg < cgLen; cg++) {
          let cgProductList = tmpProductList[categoryList[cg].id];
          for (let p = 0; p < cgProductList.length; p++) {
            cgProductList[p].carList = [];
            cgProductList[p].carNum = 0;
            for (let c = 0; c < carProList.length; c++) {
              if (cgProductList[p].id == carProList[c].productReleaseId) {
                cgProductList[p].carList.push(carProList[c]);
                cgProductList[p].carNum += carProList[c].num;
              }
            }
          }
        }
      } else {
        for (let cg = 0; cg < cgLen; cg++) {
          let cgProductList = tmpProductList[categoryList[cg].id];
          for (let p = 0; p < cgProductList.length; p++) {
            cgProductList[p].carList = [];
            cgProductList[p].carNum = 0;
          }
        }
      }
      setProductList(tmpProductList);
    }
  }, [carProList]);

  useEffect(() => {
    getCommentCountServer({ topicId: urlParms.current.orgId, appId: 'thjs_takeout_org' }).then(
      (res) => {
        if (res.code == 1) {
          setCommentHasPicCount(res.content.find((item) => item.id == 1).count);
          setCommentGoodCount(res.content.find((item) => item.id == 2).count);
          tabsList.find((item) => item.label == '评价').ext =
            '(' + res.content.find((item) => item.id == 0).count + ')';
          setTabsList(tabsList);
        }
      },
    );
  }, []);

  useEffect(() => {
    getCommentScoreServer({ topicId: urlParms.current.orgId }).then((res) => {
      if (res.code == 1) {
        setCommentScore(res.content);
      }
    });
  }, []);

  const setSelectedAddress = (address) => {
    dispatch({ type: 'productCar/setSelectedAddressTakeOut', payload: { ...address } });
    dispatch({ type: 'productCar/setSelectedAddress', payload: { ...address } });
  };

  const clearSelectedAddress = () => {
    dispatch({ type: 'productCar/setSelectedAddressTakeOut', payload: {} });
  };

  const getAllAddress = () => {
    dispatch({ type: 'giftCard/allAddressesModel', payload: { setDefaultAddress: false } });
  };

  const willChangeAddr = () => {
    if (!utils.getToken()) {
      Taro.navigateTo({
        url: '/pages/other/login/index',
      });
      return;
    } else {
      setIsOpenedAddrList(true);
    }
  };

  useEffect(() => {
    isOpenedAddrList && getAllAddress();
  }, [isOpenedAddrList]);

  useEffect(() => {
    return () => {
      clearSelectedAddress();
    };
  }, []);

  const getLocation = async () => {
    let localLocation = utils.getLocalEffectLocation();
    if (localLocation) {
      const { latitude, longitude } = localLocation;
      setCurLocation({ latitude, longitude });
    } else {
      Taro.getLocation({
        type: 'gcj02',
        isHighAccuracy: true,
        timeout: 5000,
        success: (res) => {
          const { latitude, longitude } = res;
          const timeStamp = new Date().getTime();
          setCurLocation({ latitude, longitude });
          utils.setLocalStorage('location', { latitude, longitude, timeStamp });
        },
        fail: () => {
          setCurLocation({});
        },
      });
    }
  };

  const getShopInfo = () => {
    let params = { orgId: urlParms.current.orgId };
    let { latitude, longitude } =
      Object.keys(selectedAddress).length > 0 ? selectedAddress : curLocation;
    if (latitude || longitude) {
      params.lat = latitude;
      params.lon = longitude;
    }
    dispatch({
      type: 'takeOut/getActivityOrgInfoModel',
      payload: { ...params },
    }).then((data) => {
      background.src = data.bgImage;
      setShop(data);
      if (Object.keys(selectedAddress).length > 0 && data.deliveryMoney == '-1') {
        setIsOpenedDelivery(true);
      }
    });
  };

  const dealCategoryProduct = () => {
    let allCategoryList = [];
    let allProductList = {};
    for (let c = 0; c < takeOutProductsList.length; c++) {
      let { id, name = '', iSGroupMeal = 0 } = takeOutProductsList[c];
      allCategoryList.push({ id, name, iSGroupMeal });
      let list = takeOutProductsList[c].productList || [];
      for (let p = 0; p < list.length; p++) {
        let optionObj = list[p].option ? JSON.parse(list[p].option) : {};
        let optionsObj = list[p].options ? JSON.parse(list[p].options) : {};
        let defaultOption = [];
        let defaultOptionForSku = [];
        let isMutilSku = false;
        for (let key in optionObj) {
          defaultOption.push(optionObj[key]);
          defaultOptionForSku.push({ name: key, value: optionObj[key] });
        }
        for (let key in optionsObj) {
          if (optionsObj[key].length > 1) {
            isMutilSku = true;
            break;
          }
        }
        list[p].isMutilSku = isMutilSku;
        list[p].optionStr = defaultOption.join('/');
        list[p].defaultOptionForSku = defaultOptionForSku;
        list[p].optionsObj = optionsObj;
        list[p].carList = [];
        list[p].carNum = 0;
      }
      allProductList[id] = [...list];
    }
    setCategoryList(allCategoryList);
    setHasGot(true);
    setProductList(allProductList);
    getCarProList(); //获取当前店铺购物车信息
  };

  const getCategoryProducts = () => {
    dispatch({
      type: 'takeOut/getDiscountProductTotalModel',
      payload: {
        merchantId: urlParms.current.merchantId,
        orgId: urlParms.current.orgId,
      },
    });
  };

  const getCarProList = () => {
    if (!utils.getToken()) {
      return;
    }
    let { latitude, longitude } =
      (Object.keys(selectedAddress).length > 0 ? selectedAddress : curLocation) || {};
    dispatch({
      type: 'takeOut/getProductCarListModel',
      payload: {
        orgId: urlParms.current.orgId,
        merchantId: urlParms.current.merchantId,
        type: 4,
        latitude,
        longitude,
      },
    }).then((result) => {
      const { productCarOrgList: data = [], stockLimitList = [] } = result;

      if (data.length > 0) {
        const { isInDelivery = 0, fee = 0 } = data[0];
        const { totalPayment = 0, totalPrice = 0 } = data[0];
        setDelivery({ isInDelivery, fee });
        setTotalMoney({ totalPayment, totalPrice });

        let products = data[0]?.products || [];
        for (let i = 0; i < products.length; i++) {
          let optionSelObj = JSON.parse(products[i].optionValue);
          let selOptionList = [];
          for (let key in optionSelObj) {
            selOptionList.push(optionSelObj[key]);
          }
          products[i].optionSelObj = optionSelObj;
          products[i].optionSelStr = selOptionList.join('/');
        }
        setCarProList(products);
      } else {
        setDelivery(null);
        setTotalMoney({ totalPayment: 0, totalPrice: 0 });
        setCarProList([]);
        isOpenedCar && setIsOpenedCar(false);
      }
      hasGetCar.current = true;

      // 设置 售罄列表
      setSoldGoods(stockLimitList);
    });
  };

  useDidShow(() => {
    getCarProList();
  });

  // 获取每个右侧的 bar 到顶部的距离，用来做后面的计算。
  const getEachRightItemToTop = () => {
    let obj = {};
    let totop = 0;
    // 右侧第一类肯定是到顶部的距离为 0
    obj[categoryList[0].id] = totop;
    // 循环来计算每个子类到顶部的高度
    for (let i = 1; i < categoryList.length + 1; i++) {
      totop +=
        RIGHT_BAR_HEIGHT +
        (productList[categoryList[i - 1].id].length - 1) * RIGHT_ITEM_HEIGHT_DISTANCE +
        (productList[categoryList[i - 1].id].length > 0 ? RIGHT_ITEM_HEIGHT_DISTANCE_LAST : 0);
      for (let p = 0; p < productList[categoryList[i - 1].id].length; p++) {
        totop +=
          productList[categoryList[i - 1].id][p].activityType == 3
            ? RIGHT_ITEM_HEIGHT_ZHEKOU
            : RIGHT_ITEM_HEIGHT_NORMAL;
      }
      // 这个的目的是 例如有两类，最后需要 0-1 1-2 2-3 的数据，所以需要一个不存在的 'last' 项，此项即为第一类加上第二类的高度。
      obj[categoryList[i] ? categoryList[i].id : 'last'] = totop;
    }
    return obj;
  };

  const handleMenuItem = (itemId) => {
    preventScrollHandle.current = true;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(() => {
      preventScrollHandle.current = false;
    }, 500);
    setCurLeftSelect(itemId);
    setCurRightToTop(eachRightItemToTop.current[itemId]);
  };

  const handleProListScroll = (e) => {
    if (preventScrollHandle.current) {
      return;
    }
    for (let i = 0; i < categoryList.length; i++) {
      let pre = eachRightItemToTop.current[categoryList[i].id];
      let next = eachRightItemToTop.current[categoryList[i + 1] ? categoryList[i + 1].id : 'last'];
      if (e.detail.scrollTop + 2 < next && e.detail.scrollTop + 2 >= pre) {
        setCurLeftSelect(categoryList[i].id);
        setCurLeftToTop(LEFT_ITEM_HEIGHT * i);
        break;
      }
    }
  };

  const getLastgroupProExtendDom = () => {
    if (categoryList.length > 0) {
      let lastgroupProLen = productList[categoryList[categoryList.length - 1].id].length;
      for (let i = lastgroupProLen; i < 4; i++) {
        lastgroupProExtendDom.current.push(
          <View className="product empty" key={'productEmpty' + i}></View>,
        );
      }
    }
  };

  const handleCar = () => {
    if (!utils.getToken()) {
      Taro.navigateTo({
        url: '/pages/other/login/index',
      });
      return;
    }
    carProList.length > 0 && !isOpenedCar && setIsOpenedCar(true);
  };

  const goDetail = (releasedId, minMoney, deliveryMoney) => {
    Taro.navigateTo({
      url:
        '/mainSubPack/takeOutGoodsDetail/index?releasedId=' +
        releasedId +
        '&orgId=' +
        urlParms.current.orgId +
        '&merchantId=' +
        urlParms.current.merchantId +
        '&deliveryMoney=' +
        deliveryMoney +
        '&minMoney=' +
        minMoney +
        '&orgName=' +
        shop.name,
    });
  };

  const handleSku = (product) => {
    product.orgId = urlParms.current.orgId;
    setProductCur(product);
    !isOpenedSku && setIsOpenedSku(true);
  };

  const handleClose = () => {
    isOpenedCar && setIsOpenedCar(false);
    if (isOpenedSku) {
      setIsOpenedSku(false);
      setProductCur({});
    }
    isOpenedDelivery && setIsOpenedDelivery(false);
  };

  const handleAddPro = (product, skuInfo = null) => {
    if (!utils.getToken()) {
      Taro.navigateTo({
        url: '/pages/other/login/index',
      });
      return;
    }
    dispatch({
      type: 'takeOut/addProductToCarModel',
      payload: {
        merchantId: urlParms.current.merchantId,
        orgId: urlParms.current.orgId,
        orgName: shop.name ?? '',
        productReleaseId: product.id,
        productVariantReleaseId: skuInfo ? skuInfo.id : product.variantId,
        type: 4,
        favouredId: skuInfo ? skuInfo.activityId : product.activityId,
        favouredType: skuInfo ? skuInfo.type : product.activityType,
      },
    }).then((rst) => {
      if (rst == 'success') {
        getCarProList();
      }
    });
  };

  const handlePurchaseNum = debounce(async (type, product) => {
    let { num, id, activityLimit } = product;
    if (type === 'add') {
      num++;
      if (activityLimit > 0 && num == parseInt(activityLimit) + 1) {
        Taro.showToast({
          title: '该折扣商品限购' + activityLimit + '份,超过' + activityLimit + '份恢复原价',
          icon: 'none',
          mask: false,
          duration: 2000,
        });
      }
    }
    if (type === 'sub') num--;
    if (type === 'sub' && num < 1) {
      await dispatch({
        type: 'productCar/deleteDeleteProduct',
        payload: { id },
      });
    } else {
      await dispatch({
        type: 'productCar/updateProductNum',
        payload: { id, num },
      });
    }
    getCarProList();
  }, 800);

  const goToBuy = (productToPayList = []) => {
    if (productToPayList.length == 0) {
      return;
    }

    const cartIds = productToPayList.map((v) => v.id);
    const productReleaseIds = productToPayList.map(({ productReleaseId }) => productReleaseId);

    dispatch({
      type: 'productCar/setCartShopSelectedByTakeOut',
      payload: cartIds,
    });

    dispatch({
      type: 'productCar/setCartShopProductReleaseIds',
      payload: productReleaseIds,
    });

    Taro.navigateTo({
      url:
        '/orderSubPack/confirmOrder/index?merchantId=' +
        urlParms.current.merchantId +
        '&orgId=' +
        urlParms.current.orgId +
        '&type=4',
    });
  };

  const handleGoPay = () => {
    if (!utils.getToken()) {
      Taro.navigateTo({
        url: '/pages/other/login/index',
      });
      return;
    }

    const group = checkDistributionWay(carProList);

    if (group === true) {
      goToBuy(carProList);
      return;
    }

    setDistributionWayGroup(group);
  };

  const handleCartPay = () => {
    handleClose();
    handleGoPay();
  };

  let curLeftSelectIdx = 0;
  for (let g = 0; g < categoryList.length; g++) {
    if (categoryList[g].id == curLeftSelect) {
      curLeftSelectIdx = g;
      break;
    }
  }

  let totalSelProNum = 0;
  if (carProList.length > 0) {
    carProList.map((item) => {
      totalSelProNum += parseInt(item.num);
    });
  }

  useEffect(() => {
    if (!categoryList) {
      setIsEmptyProduct(false);
      return;
    }

    if (categoryList.length === 0 && hasGot) {
      setIsEmptyProduct(true);
    } else {
      setIsEmptyProduct(false);
    }
  }, [categoryList, hasGot]);

  return (
    <View className="totalPage_takeOutShop">
      <CommentImagePreview />
      {!Taro.$isH5 && background ? (
        background.src ? (
          <View className="topBackground">
            <Image className="topBackgroundImg" src={background.src}></Image>
          </View>
        ) : (
          <View className="topBackground"></View>
        )
      ) : null}
      <View className="fontPage">
        {!Taro.$isH5 && (
          <View
            className="topBar"
            style={{
              height: Taro.$titleHeight + 'px',
              top: Taro.$statusBarHeight + 'px',
            }}
          >
            {bar && (
              <>
                {bar.back ? (
                  <Image className="backIcon" src={pBack} onclick={goBackPage} />
                ) : (
                  <View className="backIcon"></View>
                )}
                <Text className="title">{bar.title}</Text>
                <View className="backIcon"></View>
              </>
            )}
          </View>
        )}

        <View
          className="takeOutShop"
          style={{
            marginTop: Taro.$isH5 ? '0px' : Taro.$titleHeight + Taro.$statusBarHeight + 4 + 'px',
            height: Taro.$isH5
              ? '100%'
              : 'calc(100% - ' +
                Taro.$titleHeight +
                'px - ' +
                Taro.$statusBarHeight +
                'px - 4' +
                'px)',
          }}
        >
          <View className="shopInfo">
            <View className="baseInfo">
              <Imagelocation
                className="shopIcon"
                src={shop.logo}
                type="shop"
                key={'takeoutDetail' + shop.id}
              />
              <View className="base">
                <View className="name">{shop.name}</View>
                <View className="other">
                  <Text className="starTitle">
                    {typeof shop.grade !== 'undefined' ? '评分' : ''}
                  </Text>
                  <Text className="starNum">
                    {typeof shop.grade !== 'undefined' ? shop.grade : ''}
                  </Text>
                  <Text className="saleTitle">
                    {typeof shop.saleNum !== 'undefined' ? '月售' : ''}
                  </Text>
                  <Text className="saleNum">
                    {typeof shop.saleNum !== 'undefined' ? shop.saleNum + '件' : ''}
                  </Text>
                </View>
              </View>
            </View>
            {typeof shop.notice !== 'undefined' && (
              <View className="notice">{'商户公告：' + shop.notice}</View>
            )}
            {typeof shop.policy !== 'undefined' && (
              <View className="manjian customePageBackgroundStyle customePageStyle">
                {shop.policy.length > 0 && shop.policy.join(' | ')}
              </View>
            )}
          </View>

          <View id="classTypeId" className="classType">
            <Tabs tabsList={tabsList} getCurrentTab={handleTabChanged} />
          </View>

          {currentTab === 0 && isEmptyProduct && (
            <EmptyProduct
              txt="该商户暂无商品哟～"
              style={{
                height: utils.getCalcHeight(
                  '100vh',
                  // 顶部店铺信息高度
                  232,
                  // 底部配送菜单高度
                  120,
                  // 顶部状态栏高度
                  Taro.$isH5 ? '0px' : Taro.$titleHeight + Taro.$statusBarHeight + 4 + 'px',
                ),
              }}
            />
          )}

          {currentTab == 0 && !isEmptyProduct && (
            <View className={'proCnt ' + (Taro.$bottomHight ? 'proCtnMbH' : '')}>
              <ScrollView className="proMenu" scrollWithAnimation scrollY scrollTop={curLeftToTop}>
                {Object.keys(productList).length > 0 &&
                  categoryList.length > 0 &&
                  categoryList.map((item, cgIdx) => (
                    <View
                      className={['menuItem', curLeftSelectIdx === cgIdx && 'active'].join(' ')}
                      onClick={() => handleMenuItem(item.id)}
                      key={'menuItem' + item.id}
                    >
                      {curLeftSelectIdx === cgIdx && (
                        <View className="activeMenuCol customePageBackgroundStyle"></View>
                      )}
                      <Text
                        className={[
                          'menuText txtDot flex-row--center',
                          curLeftSelect === item.id && 'customePageStyle',
                        ].join(' ')}
                      >
                        {item.name}
                      </Text>
                    </View>
                  ))}
              </ScrollView>

              <ScrollView
                className="proList"
                scrollWithAnimation
                scrollY
                scrollTop={curRightToTop}
                onScroll={handleProListScroll}
              >
                {Object.keys(productList).length > 0 &&
                  categoryList.length > 0 &&
                  categoryList.map((item, groupIdx, groupArr) => (
                    <View
                      className="titleProList"
                      id={'title' + item.id}
                      key={'rightItem' + item.id + '_' + groupIdx}
                    >
                      <View className="titleName">{item.name}</View>
                      {productList[item.id] &&
                        productList[item.id].length > 0 &&
                        productList[item.id].map((product, pIdx) => (
                          <View
                            className="product"
                            onClick={() =>
                              shop.deliveryMoney != -1 &&
                              shop.isBusiness == 1 &&
                              goDetail(product.id, shop.minMoney, shop.deliveryMoney)
                            }
                            key={item.id + 'product' + product.id + '_' + pIdx}
                          >
                            <View className="imgArea">
                              <Imagelocation
                                className="img"
                                src={
                                  product.url?.indexOf('http') === 0
                                    ? product.url
                                    : sourceUrl + product.url
                                }
                              />
                              {product.activityType == 3 && (
                                <Image className="bqImg zhekou" src={pZhekou} />
                              )}
                            </View>
                            <View className="info">
                              <View className="name">{product.title || ''}</View>
                              <View className="gray">{product.optionStr || ''}</View>
                              <View className="gray">
                                月售<Text className="num">{product.monthlySale || 0}</Text>件
                              </View>
                              <View className="priceAdd">
                                <View className="price customePageStyle">
                                  <Text className="flag">¥</Text>
                                  <Text>{product.price}</Text>
                                  {product.activityType == 3 && (
                                    <Text className="flag ml4">起</Text>
                                  )}
                                </View>

                                {checkProductIsSoldOut(product, 'totalInventoryQuantity') === 0 ? (
                                  <View className="sold-out">
                                    <View className="sold-out-txt">已售罄</View>
                                  </View>
                                ) : product.isMutilSku ? (
                                  <View onClick={(e) => e.stopPropagation()}>
                                    <View
                                      className={
                                        'skuSel ' +
                                        (shop.deliveryMoney == -1 || shop.isBusiness == 0
                                          ? ''
                                          : 'customePageBackgroundStyle')
                                      }
                                      onClick={() => {
                                        shop.deliveryMoney != -1 &&
                                          shop.isBusiness == 1 &&
                                          handleSku(product);
                                      }}
                                    >
                                      选规格
                                      {product.carNum > 0 &&
                                        shop.deliveryMoney != -1 &&
                                        shop.isBusiness == 1 && (
                                          <Text className="num">{product.carNum}</Text>
                                        )}
                                    </View>
                                  </View>
                                ) : shop.deliveryMoney != -1 &&
                                  shop.isBusiness == 1 &&
                                  product.carNum > 0 ? (
                                  <View className="opCart" onClick={(e) => e.stopPropagation()}>
                                    <Icon
                                      name="a-icon_minus_huaban7fuben8"
                                      size={40}
                                      color={customeColor}
                                      onClick={() => handlePurchaseNum('sub', product.carList[0])}
                                    />
                                    <Text className="num">{product.carNum}</Text>
                                    <Icon
                                      name="icon_add"
                                      size={40}
                                      color={customeColor}
                                      onClick={() => handlePurchaseNum('add', product.carList[0])}
                                    />
                                  </View>
                                ) : (
                                  <Icon
                                    name="icon_add"
                                    size={40}
                                    color={
                                      shop.deliveryMoney == -1 || shop.isBusiness == 0
                                        ? '#cccccc'
                                        : customeColor
                                    }
                                    onClick={(e) => {
                                      e.stopPropagation();
                                      shop.deliveryMoney != -1 &&
                                        shop.isBusiness == 1 &&
                                        handleAddPro(product, null);
                                    }}
                                  />
                                )}
                              </View>
                              {product.activityType == 3 && (
                                <View className="activityDetail">
                                  <View className="actTxt customePageBorderStyle50 customePageStyle">
                                    {product.discount}折起
                                  </View>
                                </View>
                              )}
                            </View>
                          </View>
                        ))}
                      {groupIdx + 1 === groupArr.length &&
                        lastgroupProExtendDom.current.length > 0 &&
                        lastgroupProExtendDom.current}
                    </View>
                  ))}
              </ScrollView>
            </View>
          )}
          <View className="commentBox" style={{ display: currentTab == 1 ? 'flex' : 'none' }}>
            <ScrollView
              className="commentContent"
              scrollWithAnimation
              scrollY
              onScrollToLower={() => {
                refCommentList.current.nextPage();
              }}
            >
              <View className="scorePart">
                <CommentScoreInfo data={commentScore} shopScore={shop.grade || 0} />
              </View>
              <View className="commentPart">
                <View className="commentPartContent">
                  <View className="filterPart">
                    <CommentFilter
                      defaultFilter={commentFilter}
                      goodCount={commentGoodCount}
                      hasPicCount={commentHasPicCount}
                      handleFilter={handleCommentFilter}
                    />
                  </View>
                  <View className="listPart" scrollWithAnimation scrollY scrollTop={curLeftToTop}>
                    <CommentList
                      ref={refCommentList}
                      topicId={urlParms.current.orgId}
                      type={commentFilter}
                    />
                  </View>
                </View>
              </View>
            </ScrollView>
          </View>
        </View>

        <View className="takeOutShopBottom flex-column">
          <View className="bottomCtx flex-row--center">
            <View className="tab flex-column--center" onClick={handleCar}>
              <Image className="icon" src={cartImg} />
              <View className="name">购物车</View>
              {totalSelProNum > 0 && (
                <View
                  className={[
                    'gwcNum',
                    totalSelProNum > 9 && 'two',
                    totalSelProNum > 99 && 'three',
                  ].join(' ')}
                >
                  {totalSelProNum > 99 ? '99+' : totalSelProNum}
                </View>
              )}
            </View>

            <View className="feeArea flex-column-end">
              <View className="totalLine">
                <Text className="txt20">合计：</Text>
                <Text className="txt24 customePageStyle bold">¥</Text>
                <Text className="txt32 customePageStyle bold total">
                  {totalMoney.totalPayment.toFixed(2)}
                </Text>
                {totalMoney.totalPrice > totalMoney.totalPayment && (
                  <Text className="txt22 gray cheaper">{totalMoney.totalPrice.toFixed(2)}</Text>
                )}
              </View>
              <View className="sendLine txt20 black6">
                {delivery != null && delivery.isInDelivery > 0
                  ? delivery.isInDelivery == 2
                    ? '超出配送范围'
                    : delivery.fee > 0
                    ? '另需配送费¥' + delivery.fee
                    : '免配送费'
                  : ''}
              </View>
            </View>

            {totalSelProNum > 0 && totalMoney.totalPrice >= shop.minMoney ? (
              <View
                className="btnPay flex-row-center-center customePageBackgroundStyle"
                onClick={handleGoPay}
              >
                去结算
              </View>
            ) : (
              <View className="btnPay unableBtn flex-row-center-center">¥{shop.minMoney}起送</View>
            )}
          </View>
          {Taro.$bottomHight && <View className="bottomHt"></View>}
        </View>

        {(shop.deliveryMoney == -1 || shop.isBusiness == 0) && (
          <View className={'outDelivery ' + (Taro.$bottomHight ? 'bhigh' : '')}>
            <View
              className="outDeliveryCtx flex-row-center-center"
              onClick={() => shop.isBusiness == 1 && setIsOpenedDelivery(true)}
            >
              <Text className="outDeliveryText">
                {shop.isBusiness == 0
                  ? '本店已休息（' + shop.businessTime + '开始营业）'
                  : '本店超出配送范围'}
              </Text>
              {shop.isBusiness == 1 && <Image className="upicon" src={pUpWhite} />}
            </View>
            {Taro.$bottomHight && <View className="bottomHt"></View>}
          </View>
        )}

        <ShoppingCarList
          isOpened={isOpenedCar}
          totalSelProNum={totalSelProNum}
          totalSelProMoney={totalMoney.totalPayment}
          totalPrice={totalMoney.totalPrice}
          minMoney={shop.minMoney}
          deliveryMoney={shop.deliveryMoney}
          delivery={delivery}
          carProList={carProList}
          handlePurchaseNum={handlePurchaseNum}
          handleClose={handleClose}
          handlePay={handleCartPay}
        />

        <SkuSelect
          isOpened={isOpenedSku}
          product={productCur}
          handleAddPro={handleAddPro}
          handlePurchaseNum={handlePurchaseNum}
          handleClose={handleClose}
          dispatch={dispatch}
        />

        <Delivery
          isOpened={isOpenedDelivery}
          onClose={handleClose}
          curShopId={shop.id}
          handleAddr={willChangeAddr}
        />

        <AddressSelect
          isOpened={isOpenedAddrList}
          handleClose={(address = null) => {
            setIsOpenedAddrList(false);
            if (address) {
              setSelectedAddress(address);
            }
          }}
          allAddresses={allAddresses}
        />

        <DistributionWayLayout
          {...{
            isOpened: !!distributionWayGroup,
            onClose: () => {
              setDistributionWayGroup();
            },
            value: distributionWayGroup,
            onChange: (theProductList) => {
              goToBuy(theProductList);
            },
          }}
        />
      </View>

      <Sold goods={soldGoods} onClose={handleSoldClose} />
    </View>
  );
};

export default connect(({ takeOut, giftCard, productCar }) => ({
  takeOutProductsList: takeOut.takeOutProductsList,
  allAddresses: giftCard.allAddresses,
  selectedAddress: productCar.selectedAddressTakeOut,
}))(TakeOutShopPage);
